from django.shortcuts import render
from random import randint

from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
# from  meiduoProject.libs.yuntongxun.sms import CCP
# 引入短信接口
from meiduoProject.libs.SMSYuntongxun.SMSMessgeCode import send_message
from celery_tasks.sms.tasks import send_sms_code,test_code
from . import constants
import logging
logger = logging.getLogger('django')
# Create your views here.
class SMSCodeView(APIView):
    """短信验证码"""
    def get(self,request,mobile):
        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        # 先从redis获取手机号发送标记
        send_flag=redis_conn.get('send_flag_%s'%mobile)
        if send_flag:
            return Response({"message":"手机频繁发送短信"},status=status.HTTP_400_BAD_REQUEST)
        # 生成验证码
        # sms_code='%06d'%randint(1,99999) # 发送6位验证码
        sms_code='%04d'%randint(1,999) # 个人测试仅支持1~4位验证码
        #
        logger.info(sms_code)
        # 创建redis管道
        pl=redis_conn.pipeline()
        # 把验证码存储到redis数据库中
        pl.setex('sms_%s'%mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        # 存储一个标记，表示此手机号已发送过短信 ，标记有效期为60s
        pl.setex('send_flag_%s'%mobile,constants.SEND_SMS_CODE_INTERVAL,constants.SMS_CODE_PONE_SIGN)
        # 执行管道
        pl.execute()
        # 利用第三方容联云通讯发送短信验证码
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        # send_message(mobile,(sms_code,constants.SMS_CODE_REDIS_EXPIRES//60))
        # 触发异步任务，将其添加到celery任务队列
        test_code.delay()
        send_sms_code.delay(mobile,sms_code)
        # 响应
        return Response({'code':200,'data':sms_code,'message':'短信验证码已发送'})